import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/extension/date_string_extension.dart';
import 'package:xvideos/hj_model/comment/comment_model.dart';
import 'package:xvideos/hj_model/comment/reply_model.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/comment/cell/reply_comment_item.dart';
import 'package:xvideos/hj_page/home_business/widget/image_scale_view.dart';
import 'package:xvideos/hj_page/home_business/widget/user_avatar.dart';
import 'package:xvideos/hj_page/home_business/widget/user_name_view.dart';
import 'package:xvideos/hj_page/comment/widget/comment_rich_text.dart';
import 'package:xvideos/hj_utils/api_service/comment_service.dart';
import 'package:xvideos/hj_utils/api_service/common_service.dart';
import 'package:xvideos/hj_utils/date_time_util.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/debug_log.dart';
import 'package:like_button/like_button.dart';

import '../../../tools_base/widget/net_image_widget.dart';

class CommentItemConfig {
  Color nameColor; //名颜色
  Color contentColor; //内容颜色
  Color timeColor; //时间颜色
  Color expandColor; //展开颜色
  Color toUserColor; //回复用户颜色
  Color commentBgColor; //回复背景颜色
  Color commentTxColor; //回复背景颜色
  Color lineColor;
  int iconType; //1-暗黑背景 2-白色背景

  CommentItemConfig({
    this.nameColor = const Color(0xffEEC76B),
    this.contentColor = const Color(0xffffffff),
    this.timeColor = const Color(0x99ffffff),
    this.expandColor = const Color(0x993476FF),
    this.toUserColor = const Color(0x4Dffffff),
    this.commentBgColor = const Color(0x1affffff),
    this.commentTxColor = const Color(0x4cffffff),
    this.iconType = 1,
    this.lineColor = const Color(0x0fffffff),
  });
}

class CommentItem extends StatefulWidget {
  final CommentModel comment;
  final CommentItemConfig? config; //配置信息
  final String objId;

  // 点赞的内部操作就行

  Function(CommentModel, {ReplyModel? reply})? replyHandler;

  CommentItem(
    this.comment, {
    super.key,
    required this.objId,
    this.replyHandler,
    this.config,
  });

  @override
  State<CommentItem> createState() => _CommentItemState();
}

class _CommentItemState extends State<CommentItem> {
  CommentModel get comment => widget.comment;

  CommentItemConfig? get config => widget.config ?? CommentItemConfig();
  late ValueNotifier<bool> likeValueNof;
  bool _isLoadingMore = false;
  int page = 1;
  bool isExpand = false;

  @override
  void initState() {
    likeValueNof = ValueNotifier(comment.isLike ?? false);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: GestureDetector(
          onTap: () {},
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      UserAvatar(
                        size: 40,
                        model: Publisher()
                          ..uid = comment.userID
                          ..portrait = comment.userPortrait
                          ..superUser = (comment.superUser ?? false),
                        showVip: false,
                      ), //头像
                      12.sizeBoxW,
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                              children: [
                                UserNameView(
                                  name: comment.userName,
                                  isVip: (comment.vipLevel ?? 0) > 0,
                                  nameColor: Color(0xff9A9A9A),
                                ),
                                if ((comment.vipLevel ?? 0) > 0) ...[
                                  4.sizeBoxW,
                                  Image.asset("vip_v.webp".commentPath, width: 16),
                                ]
                              ],
                            ),
                            8.sizeBoxH,
                            CommentRichText(model: comment),
                            if (comment.image?.isNotEmpty == true)
                              GestureDetector(
                                onTap: () {
                                  Get.to(ImageScaleView(url: comment.image, isPage: true));
                                },
                                child: Container(
                                  margin: EdgeInsets.only(top: 6),
                                  alignment: Alignment.centerLeft,
                                  constraints: BoxConstraints(maxWidth: 150),
                                  child: NetworkImageLoader(imageUrl: comment.image ?? ""),
                                ),
                              ),
                            8.sizeBoxH,
                            Row(
                              children: [
                                Text(
                                  comment.createdAt?.utcYMDHM() ?? "",
                                  style: TextStyle(
                                    color: Color(0x73FFFFFF),
                                    fontSize: 12,
                                  ),
                                ),
                                const Spacer(),
                                if (!comment.isOfficial && !comment.isHideLikeOrComment) ...[
                                  ValueListenableBuilder(
                                    valueListenable: likeValueNof,
                                    builder: (context, value, child) => Row(
                                      children: [
                                        LikeButton(
                                          isLiked: value,
                                          onTap: (isLiked) {
                                            return likeOrCancelLikeAction();
                                          },
                                          size: 20,
                                          likeBuilder: (isLiked) {
                                            return Image.asset(
                                                isLiked ? 'like_red.webp'.commentPath : 'like_white.webp'.commentPath);
                                          },
                                        ),
                                        SizedBox(width: 2),
                                        Text(
                                          "${comment.likeCount?.humanizeFormatDefault("0") ?? "0"}",
                                          style: TextStyle(
                                            color: Color(0xE5FFFFFF),
                                            fontSize: 12,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  12.sizeBoxW,
                                  GestureDetector(
                                    onTap: () {
                                      widget.replyHandler?.call(comment);
                                    },
                                    child: Image.asset(
                                      'msg_icon.png'.commentPath,
                                      width: 20,
                                      height: 20,
                                    ),
                                  ),
                                ],
                              ],
                            ),
                            _buildReplys(),
                            // 展开更多评论
                            if ((comment.info?.length ?? 0) > 0) _buildShowMoreReply(),
                          ],
                        ),
                      ),
                    ],
                  ),
                  18.sizeBoxH,
                  Divider(height: 1, color: config?.lineColor),
                  18.sizeBoxH,
                ],
              ),
              if ((comment.isGodComment ?? false))
                Positioned(
                  right: 8,
                  top: -10,
                  child: Transform.rotate(
                    angle: pi / 60,
                    child: Image.asset(
                      'god_comment.webp'.commentPath,
                      width: 72,
                      height: 60,
                    ),
                  ),
                ),
            ],
          )),
    );
  }

  Widget _buildShowMoreReply() {
    final diff = (comment.commCount ?? 0) - (isExpand ? (comment.info?.length ?? 0) : 1);

    // _loadingState = setState;
    var length = comment.info?.length ?? 0;
    if (length > 1 && isExpand) {
      return GestureDetector(
        onTap: () {
          isExpand = false;
          setState(() {});
        },
        child: Container(
          padding: EdgeInsets.only(top: 12),
          child: Row(
            children: [
              Container(width: 20, height: 1, color: Color(0xff989898)),
              4.sizeBoxW,
              Text(
                "收起${comment.commCount ?? 0}条回复",
                style: TextStyle(
                  fontSize: 12,
                  color: Color(0xff989898),
                  fontWeight: FontWeight.w500,
                ),
              ),
              2.sizeBoxW,
              Transform.rotate(
                angle: pi,
                child: Image.asset("arrow_down.webp".commentPath, width: 16),
              ),
            ],
          ),
        ),
      );
    }
    if (diff <= 0) return const SizedBox.shrink();
    return Container(
      padding: EdgeInsets.only(top: 12),
      child: Row(
        children: [
          if (_isLoadingMore)
            Container(
              padding: const EdgeInsets.only(left: 6),
              child: const CupertinoActivityIndicator(
                color: Colors.white,
                radius: 8,
              ),
            )
          else
            Row(
              children: [
                InkWell(
                  onTap: expandMoreReply,
                  child: Row(
                    children: [
                      Container(width: 20, height: 1, color: Color(0xff989898)),
                      4.sizeBoxW,
                      Text(
                        ((comment.info?.length ?? 0) > 99) ? '展开更多回复' : '展开$diff条回复',
                        style: TextStyle(
                          fontSize: 12,
                          color: Color(0xff989898),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      2.sizeBoxW,
                      Image.asset("arrow_down.webp".commentPath, width: 16),
                    ],
                  ),
                ),
              ],
            ),
        ],
      ),
    );
  }

  // 展开回复
  expandMoreReply() async {
    if (comment.info?.isNotEmpty != true) {
      comment.commCount = 0;
      setState(() {});
      return;
    }
    if (_isLoadingMore) return;
    _isLoadingMore = true;
    setState(() {});
    isExpand = true;
    try {
      if (comment.haveMoreData ?? false) {
        final curTime = DateTimeUtil.format2utc(DateTime.now());
        final fastId = comment.info!.first.id ?? '';
        final result = await CommentService.getReplyList(
            widget.objId, comment.id ?? '', curTime, comment.replyPageIndex ?? page, 5, fastId);
        comment.haveMoreData = result?.hasNext ?? false;
        comment.info?.addAll(result?.list ?? []);
        comment.isRequestReply = false;
        if (result?.hasNext == true) page += 1;
        if (result?.hasNext ?? false) {
          comment.replyPageIndex = (comment.replyPageIndex ?? 0) + 1;
        } else {
          comment.commCount = comment.info?.length ?? 0;
        }
      }
    } catch (e) {
      debugLog(e);
    }
    _isLoadingMore = false;
    if (mounted) setState(() {});
  }

  Future<bool> likeOrCancelLikeAction() async {
    final islike = comment.isLike ?? false;
    bool result;
    if (!islike) {
      result = await CommonService.sendLike(comment.id ?? '', 'COMMENT');
      if (result) comment.likeCount = (comment.likeCount ?? 0) + 1;
    } else {
      result = await CommonService.cancelLike(comment.id ?? '', 'COMMENT');
      if (result) comment.likeCount = (comment.likeCount ?? 1) - 1;
    }
    if (result) comment.isLike = !islike;
    likeValueNof.value = comment.isLike!;
    return likeValueNof.value;
  }

  Widget _buildReplys() {
    if (comment.info?.isEmpty ?? true) return const SizedBox.shrink();

    var length = comment.info?.length ?? 0;
    if (length > 1 && !isExpand) {
      length = 1;
    }
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: length,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return ReplyCommentItem(
            comment.info![index],
            replyHandler: (reply) {
              widget.replyHandler?.call(comment, reply: reply);
            },
            config: config,
          );
        },
      ),
    );
  }
}
